#include "psserver.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/epoll.h>

CPSServer::CPSServer(IPSMonitor* p, FnCreateClient fn)
{
	m_sock = -1;
	m_monitor = p;
	m_fnCreateClient = fn;
}

CPSServer::~CPSServer()
{
	if(-1 != m_sock)
	{
		close(m_sock);
	}
}

bool CPSServer::FindClient(unsigned int id, IPSClientContext** pContext)
{
	return false;
}
		
int CPSServer::GetEventFd()
{
	return m_sock;
}

void CPSServer::OnEventIn()
{
	sockaddr_in			addr	= {0};
	socklen_t			len		= sizeof(addr);
	int					sock;

	sock = accept(m_sock, (sockaddr*)&addr, &len);
	if(-1 != sock)
	{
		if(NULL != m_fnCreateClient)
		{
			m_fnCreateClient(sock, m_monitor);
		}
		else
		{
			close(sock);
		}
	}
}

void CPSServer::OnEventOut()
{
}

void CPSServer::OnEventPri()
{
}

void CPSServer::OnEventError()
{
}

/*
 * 开始服务
 */
bool CPSServer::Start(uint16_t port, uint32_t ip)
{
	sockaddr_in			addr		= {0};
	int					opt			= 1;

	if(-1 != m_sock)
	{
		close(m_sock);
	}
	
	m_sock = socket(AF_INET, SOCK_STREAM, 0);
	if(-1 == m_sock)
	{
		return false;
	}

	setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, (char *)&opt, sizeof(opt));
	addr.sin_family = AF_INET;
	addr.sin_port = htons(port);
	addr.sin_addr.s_addr = ip;
	if( bind(m_sock, (sockaddr*)&addr, sizeof(addr)) )
	{
		return false;
	}

	if( listen(m_sock, 0x7fffffff) )
	{
		return false;
	}

	if( false == m_monitor->AddMonitor(this, EPOLLIN))
	{
		return false;
	}
	return true;
}
